package me.qingy.programmatic;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

/**
 * 字符替换
 *
 * @author qingy
 * @since 2021/8/18
 */
public class DefangIP {

    public String defangIPAddr1(String address) {
        char[] chars = address.toCharArray();
        char[] result = new char[chars.length + 2 * 3];
        int k = 0;
        for (char c : chars) {
            if (c == '.') {
                result[k++] = '[';
                result[k++] = '.';
                result[k++] = ']';
            } else {
                result[k++] = c;
            }
        }
        return new String(result);
    }

    public String defangIPAddr2(String address) {
        char[] chars = address.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (char c : chars) {
            if (c == '.'){
                sb.append("[.]");
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    @Test
    public void testDefangIPAddr() {
        Assertions.assertEquals("1[.]1[.]1[.]1", defangIPAddr2("1.1.1.1"));
        Assertions.assertEquals("255[.]100[.]50[.]0", defangIPAddr2("255.100.50.0"));
    }
}
